package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = UserContext.getCurrentUser();
        // 判断用户是否是超级管理员,不是超管,获取请求的访问方法
        if (employee.isAdmin()){
            return true;
        }
        HandlerMethod methods = (HandlerMethod) handler;
        RequiredPermission permission = methods.getMethodAnnotation(RequiredPermission.class);
        System.out.println("toString:"+permission.toString());
        System.out.println("name:"+permission.name());
        System.out.println("expression:"+permission.expression());
        // 判断权限是否为空,如果权限为空,放行
        if (permission == null){
            return true;
        }
        // 如果权限数据不为空,则取出来与数据库匹配
        String expression = permission.expression();
        List<String> expressions = UserContext.getExpression();
        if (expressions.contains(expression)){
            return true;
        }
        // 如果不存在,转发到错误页面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;
    }

}
